package app.fitness.fragment;

import iterface.ITaskCallBacks;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import utils.Utils;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.razer.android.nabuopensdk.AuthCheckCallback;
import com.razer.android.nabuopensdk.interfaces.NabuAuthListener;
import com.razerzone.android.fitness.ActivityFitness;
import com.razerzone.android.fitness.R;

import controller.DownloadImageAsync;
import controller.UserProfileDataAsync;
import define.Constants;
import define.DashBoard;
import define.Language;
import define.PersonalData;
import define.UserProfile;
import define.WelcomeNabu;

public class PersonalDataFragment extends Fragment implements OnClickListener {
	/**
	 * Fragment section
	 */
	public static DialogFragment mDf;
	private Fragment mFm = null;

	/**
	 * Interface section
	 */
	public static ITaskCallBacks iTaskCallBacks;

	/**
	 * String section
	 */
	public static boolean IS_FIRST_TIME = true;

	/**
	 * View section
	 */
	private Button mBtnNext;
	public static EditText mEtBirthdate;
	public static EditText mEtGender;
	public static EditText mEtHeight;
	public static EditText mEtWeight;
	public static ImageButton mIbtnAvatar;
	public static TextView mTvNickName;

	/**
	 * The others section
	 */
	// private Handler mHandler;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		iTaskCallBacks = (ITaskCallBacks) activity;
	}

	@Override
	public void onClick(View v) {
		if (!UserProfile.userProfileData.isEmpty()) {
			mFm = new GoalSettingsFragment();

			// Transfer to Goal fragment
			getFragmentManager().beginTransaction()
					.replace(R.id.fr_content_activity_fitness, mFm)
					.commitAllowingStateLoss();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// mHandler = new Handler();

		Constants.utils = new Utils(getActivity());
		if (!Constants.utils.isNetworkOnline()) {
			// If there is error
			// Toast.makeText(
			// getActivity(),
			// getActivity().getString(
			// R.string.toast_network_was_disconnected),
			// Toast.LENGTH_SHORT).show();
			//
			// try {
			// Thread.sleep(1500);
			// } catch (InterruptedException e) {
			// e.printStackTrace();
			// }

			// Exit the application
			android.os.Process.killProcess(android.os.Process.myPid());
		}

		/**
		 * Authenticate first and begin get Data from server
		 */
		if (define.UserProfile.userProfileData.isEmpty()) {
			getData(getActivity());
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			final Bundle savedInstanceState) {
		/**
		 * Set Orientation for page
		 */
		getActivity().setRequestedOrientation(
				ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		// Inflate the layout for this fragment
		View v = inflater.inflate(R.layout.fragment_personal_data, container,
				false);

		initialVariables(v);

		mBtnNext.setOnClickListener(this);

		initialData(getActivity());

		return v;
	}

	@Override
	public void onDetach() {
		super.onDetach();

		iTaskCallBacks = null;
	}

	/**
	 * Initialize methods
	 */

	public static void initialData(Context context) {
		/**
		 * Show User Profile data
		 */
		if (!UserProfile.userProfileData.isEmpty()) {
			String str = UserProfile.userProfileData.getBirthDate();

			// parse the String "29/07/2013" to a java.util.Date object
			Date date;
			try {
				date = new SimpleDateFormat("dd MM yyyy").parse(str);
				// format the java.util.Date object to the desired format
				String formattedDate = new SimpleDateFormat("dd - MMM - yyyy")
						.format(date);

				mEtBirthdate.setText(context.getString(R.string.birthdate__)
						+ formattedDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			switch (Utils.checkLanguageInSettings()) {
			case Language.CHINESE:
				if (UserProfile.userProfileData.getGender().equals("male")) {
					mEtGender.setText(context.getString(R.string.gender__)
							+ context.getString(R.string.male));
				} else {
					mEtGender.setText(context.getString(R.string.gender__)
							+ context.getString(R.string.female));
				}
				break;
			case Language.ENGLISH:
				mEtGender.setText(context.getString(R.string.gender__)
						+ UserProfile.userProfileData.getGender()
								.substring(0, 1).toUpperCase()
						+ UserProfile.userProfileData.getGender().substring(1)
								.toLowerCase());
				break;
			}

			mEtHeight.setText(context.getString(R.string.height__)
					+ UserProfile.userProfileData.getHeight() + " "
					+ PersonalData.CM);
			mEtWeight.setText(context.getString(R.string.weight__)
					+ UserProfile.userProfileData.getWeight() + " "
					+ PersonalData.KG);
			mTvNickName.setText(UserProfile.userProfileData.getNickName());

			/**
			 * Set avatar for user
			 */
			// Load image
			if (DownloadImageAsync.getBitmap() != null) {
				mIbtnAvatar.setImageBitmap(DownloadImageAsync.getBitmap());
			} else {
				new DownloadImageAsync(mIbtnAvatar)
						.execute(define.UserProfile.userProfileData
								.getUrlAvatar());
			}
		}
	}

	private void initialVariables(View v) {
		mBtnNext = (Button) v.findViewById(R.id.btn_next_in_personal_data);
		mEtBirthdate = (EditText) v
				.findViewById(R.id.et_birthdate_in_personal_data);
		mEtGender = (EditText) v.findViewById(R.id.et_gender_in_personal_data);
		mEtHeight = (EditText) v.findViewById(R.id.et_height_in_personal_data);
		mEtWeight = (EditText) v.findViewById(R.id.et_weight_in_personal_data);
		mIbtnAvatar = (ImageButton) v
				.findViewById(R.id.ibtn_avatar_in_personal_data);
		mTvNickName = (TextView) v
				.findViewById(R.id.tv_nickname_in_personal_data);
	}

	/**
	 * Basic methods
	 */
	public static void getData(final Context context) {
		if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
			if (iTaskCallBacks != null) {
				iTaskCallBacks.onBeginReceiveData();
			}

			if (Constants.nabuSDK != null) {
				Constants.nabuSDK.initiate(context, Constants.APP_ID,
						Constants.SCOPE, new NabuAuthListener() {

							@Override
							public void onAuthSuccess(String arg0) {
								Constants.nabuSDK.checkAppAuthorized(context,
										new AuthCheckCallback() {

											@Override
											public void onSuccess(boolean result) {
												/**
												 * If user already signed in,
												 * Save into Shared Preferences,
												 * to confirm in next time,
												 * directly to Dash Board
												 * Fragment page, skip some
												 * pages
												 */
												SplashScreenFragment.mSpEditor
														.putBoolean(
																WelcomeNabu.IS_ONCE,
																true);
												SplashScreenFragment.mSpEditor
														.commit();

												authSuccess(context);
											}

											@Override
											public void onFailed(String result) {
												/**
												 * Deleted cache before exit
												 */
												Utils.clearApplicationData(context);

												try {
													Thread.sleep(2000);
												} catch (InterruptedException e) {
													e.printStackTrace();
												}

												android.os.Process
														.killProcess(android.os.Process
																.myPid());
											}
										});
							}

							@Override
							public void onAuthFailed(String error) {
								((Activity) context).finish();
							}
						});
			}
		} else {
			// Exit the application
			android.os.Process.killProcess(android.os.Process.myPid());
		}
	}

	private static void authSuccess(Context context) {
		/**
		 * Begin get Fitness data from Razer server, included : Steps, Climb,
		 * Distance, Calories, Sleep
		 */
		if (ActivityFitness.mFm
				.findFragmentById(R.id.fr_content_activity_fitness).getClass()
				.getSimpleName()
				.equals(PersonalDataFragment.class.getSimpleName())) {
			PersonalData.mFmPersonalData = new PersonalDataFragment();

			/**
			 * Need define how to maintain downloading data progress while
			 * change orientation of the device
			 */
			// Call new thread to get User Profile data
			new UserProfileDataAsync(context)
					.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}

		if (ActivityFitness.mFm
				.findFragmentById(R.id.fr_content_activity_fitness).getClass()
				.getSimpleName()
				.equals(DashBoardFragment.class.getSimpleName())) {
			DashBoard.mFmDashBoard = new DashBoardFragment();

			/**
			 * Need define how to maintain downloading data progress while
			 * change orientation of the device
			 */
			// Call new thread to get User Profile data
			new UserProfileDataAsync(context)
					.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}
	}
}
